package com.jason.item.service.impl;

import com.jason.item.dao.ItemMapper;
import com.jason.item.dao.ItemStockMapper;
import com.jason.item.dao.entity.Item;
import com.jason.item.dao.entity.ItemStock;
import com.jason.item.model.ItemModel;
import com.jason.item.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class ItemServiceImpl implements ItemService {

    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private ItemStockMapper itemStockMapper;



    @Transactional(rollbackFor=Exception.class)
    @Override
    public ItemModel createItem(ItemModel itemModel) {

        Item item = itemModel.getItem();
        itemMapper.insertSelective(item);

        itemModel.setId(item.getId());

        ItemStock itemStock = itemModel.getItemStock();
        itemStockMapper.insertSelective(itemStock);

        return itemModel;
    }
    /**
     *
     * <p> 修改商品 </p>
     * @Param [itemModel]
     * @return com.jason.item.model.ItemModel
     * @date
     * @author Jason
     **/
    @Transactional(rollbackFor=Exception.class)
    @Override
    public ItemModel updateItem(ItemModel itemModel) {

        Item item = itemModel.getItem();
        itemMapper.updateByPrimaryKeySelective(item);
        ItemStock itemStock = itemModel.getItemStock();
        itemStockMapper.updateByItemId(itemStock);

        return itemModel;
    }

    @Override
    public List<ItemModel> listItem() {

        List<Item> itemList = itemMapper.selectAll();

        List<ItemModel> itemModelList = itemList.stream().map(item -> {
            ItemStock itemStock = itemStockMapper.selectByItemId(item.getId());

            ItemModel itemModel = ItemModel.convertByItem(item);
            if (itemStock != null) {
                itemModel.setStock(itemStock.getStock());
            }
            return itemModel;
        }).collect(Collectors.toList());

        return itemModelList;
    }

    @Override
    public ItemModel getItemById(Integer id) {

        Item item = itemMapper.selectByPrimaryKey(id);
        ItemStock itemStock = itemStockMapper.selectByItemId(id);

        ItemModel itemModel = ItemModel.convertByItem(item);
        itemModel.setStock(itemStock.getStock());

        return itemModel;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void removeItemById(Integer id) {
        int i = itemMapper.deleteByPrimaryKey(id);
        int i2 =itemStockMapper.deleteByItemId(id);
    }


}
